package com.ccp.dev.qbdms.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Base64Util {
    /**
     * 远程服务器
     * @param contentpath
     * @return
     * @throws IOException
     */
    public static String pdfToBase64(String contentpath) throws  IOException {
        InputStream is = null;
        String url = contentpath;
        URL url2 = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) url2.openConnection();
        conn.setDoInput(true);
        conn.connect();
        is =  conn.getInputStream();

        // 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        // 读取图片字节数组
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = is.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            data = swapStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return new BASE64Encoder().encode(data).replace("\n", "").replace("\r", "").replace("\t","");
    }


    /**
     * <p>将文件转成base64 字符串</p>
     * @param path 文件路径
     * @return
     * @throws Exception
     */
    public static String encodeBase64File(String path)  {
        try {
            File file = new File(path);
            FileInputStream inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int)file.length()];
            inputFile.read(buffer);
            inputFile.close();
            return new BASE64Encoder().encode(buffer).replace("\n", "").replace("\r", "");
        }catch (Exception e){
            e.printStackTrace();
        }
            return "";
    }


    /**
     * <p>将文件转成base64 字符串</p>
     * @param path 文件路径
     * @return
     * @throws Exception
     */
    public static String encodeBase64FileBig(String path)  {
        try {
            StringBuffer sb=new StringBuffer();
            int bufSize = 1024*10;
            byte[] bs = new byte[bufSize];
            ByteBuffer byteBuf = ByteBuffer.allocate(1024);
            FileChannel channel = new RandomAccessFile(path, "r").getChannel();
            while (channel.read(byteBuf) != -1) {
                int size = byteBuf.position();
                byteBuf.rewind();
                byteBuf.get(bs);
                // 把文件当字符串处理，直接打印做为一个例子。
                System.out.print(new String(bs, 0, size));
                byteBuf.clear();
                sb.append(new BASE64Encoder().encode(bs).replace("\n", "").replace("\r", ""));
            }
            return sb.toString();
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 将base64转换为指定文件
     * @author 张朝阳
     * @param str base64串
     * @param fileName 文件全名,包含路径
     */
    public static void decodeBase64ToFile(String str,String fileName){
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(str);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            OutputStream out = new FileOutputStream(fileName);
            out.write(bytes);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}